package com.shou.service;

import com.shou.mapper.UserMapper;
import com.shou.pojo.Activity;
import com.shou.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Override
    public void addUser(User user) {
        userMapper.registerUser(user);
    }

    @Override
    public boolean authenticateUser(String username, String password) {
        User user = userMapper.getUserByUsername(username);
        if(user!=null&&user.getPassword().equals(password)){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean registerUser(String username, String password) {
        // Create a User object with the provided username, password, and a default role
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        //newUser.setRole("USER"); // Adjust the default role based on your requirements

        try {
            // Use the userMapper instance to call the registerUser method
            int rowsAffected = userMapper.registerUser(newUser);

            // Check if the registration was successful (rowsAffected > 0)
            return rowsAffected > 0;
        } catch (Exception e) {
            // Handle exceptions appropriately
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public User findById(int id) {
        return userMapper.findById(id);
    }

    @Override
    @Transactional
    public void removeActivityFromUser(int userId, int activityId) {
        userMapper.removeActivityFromUser(userId, activityId);
    }


    @Override
    @Transactional
    public void addActivityToUser(int userId, Activity activity) {
        userMapper.addActivityToUser(userId, activity);
    }

    @Override
    public boolean loginUser(User user) {
        // 实现具体的登录逻辑，例如验证用户名密码等
        User storedUser = userMapper.findByUsername(user.getUsername());
        return storedUser != null && storedUser.getPassword().equals(user.getPassword());
    }

    @Override
    @Transactional
    public void registerUser(User user) {
        // 实现具体的注册逻辑，例如密码加密、用户名唯一性验证等
        userMapper.registerUser(user);
    }
}
